package top.jacktgq.lock.reentrantLock;

import java.util.concurrent.locks.LockSupport;

import top.jacktgq.utils.LogUtils;

/**
 * 
 * @Title: TestReentrantLock.java 
 * @Package top.jacktgq.lock 
 * @Description: 多线程交替输出：线程1输出 a 5次，线程2输出 b 5次，线程3输出 c 5次
 * @author CandyWall   
 * @date 2020年11月1日 下午5:49:07 
 * @version V1.0
 */
public class Demo6_4_multiThreadRunInTurn {
	private static Thread t1;
	private static Thread t2;
	private static Thread t3;

	public static void main(String[] args) {
		ParkUnpark parkUnpark = new ParkUnpark(5);
		t1 = new Thread(() -> {
			parkUnpark.print("a", t2);
		}, "t1");
		t2 = new Thread(() -> {
			parkUnpark.print("b", t3);
		}, "t2");
		t3 = new Thread(() -> {
			parkUnpark.print("c", t1);
		}, "t3");
		t1.start();
		t2.start();
		t3.start();
		
		//先由主线程首先唤醒线程t1
		LockSupport.unpark(t1);
	}	
}

/*
 *	输出内容	等待标记	下一个标记 
 * 	   a	  1		   2
 *     b      2        3
 *     c      3        1
 */
class ParkUnpark {
	//循环次数
	private int loopNumber;
	public ParkUnpark(int loopNumber) {
		this.loopNumber = loopNumber;
	}
	
	/**
	 * 
	 * @param str			：打印内容
	 * @param nextThread	：下一个待唤醒的线程
	 */
	public void print(String str, Thread nextThread) {
		for(int i = 0; i < loopNumber; i++) {
			LockSupport.park();
			LogUtils.log("ParkUnpark", str);
			LockSupport.unpark(nextThread);
		}
	}
}
